package net.lahuobao.mall.controller.admin;

import net.lahuobao.mall.entity.admin.MallArticleEntity;
import net.lahuobao.mall.entity.admin.MallJsonResult;
import net.lahuobao.mall.service.admin.MallArticleServiceI;
import org.apache.log4j.Logger;
import org.jeecgframework.core.beanvalidator.BeanValidators;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.DataGridReturn;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**   
 * @Title: Controller
 * @Description: 文章管理
 * @author zhangdaihao
 * @date 2016-08-25 11:01:48
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/mallArticleController")
public class MallArticleController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(MallArticleController.class);

	@Autowired
	private MallArticleServiceI mallArticleService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private Validator validator;
	


	/**
	 * 文章管理列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "list")
	public ModelAndView list(HttpServletRequest request) {
		return new ModelAndView("net/lahuobao/mall/admin/mallArticleList");
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(MallArticleEntity mallArticle,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		CriteriaQuery cq = new CriteriaQuery(MallArticleEntity.class, dataGrid);
		cq.addOrder("sort", SortDirection.asc);
		//查询条件组装器
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, mallArticle, request.getParameterMap());
		this.mallArticleService.getDataGridReturn(cq, true);
		TagUtil.datagrid(response, dataGrid);
	}

	/**
	 * 删除文章管理
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(MallArticleEntity mallArticle, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		mallArticle = systemService.getEntity(MallArticleEntity.class, mallArticle.getId());
		message = "文章管理删除成功";
		mallArticleService.delete(mallArticle);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加文章管理
	 * 
	 * @param
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(MallArticleEntity mallArticle, HttpServletRequest request) {
		String message = null;
		AjaxJson j = new AjaxJson();
		if (StringUtil.isNotEmpty(mallArticle.getId())) {
			message = "文章管理更新成功";
			MallArticleEntity t = mallArticleService.get(MallArticleEntity.class, mallArticle.getId());
			try {
				MyBeanUtils.copyBeanNotNull2Bean(mallArticle, t);
				mallArticleService.saveOrUpdate(t);
				systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
			} catch (Exception e) {
				e.printStackTrace();
				message = "文章管理更新失败";
			}
		} else {
			message = "文章管理添加成功";
			HttpSession session = ContextHolderUtils.getSession();
			TSUser user = (TSUser)session.getAttribute(ResourceUtil.LOCAL_CLINET_USER);
			mallArticle.setCreateuserid(user.getId());
			mallArticle.setCreatetime(new Date());
			mallArticleService.save(mallArticle);
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 文章管理列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(MallArticleEntity mallArticle, HttpServletRequest req) {
		if (StringUtil.isNotEmpty(mallArticle.getId())) {
			mallArticle = mallArticleService.getEntity(MallArticleEntity.class, mallArticle.getId());
			req.setAttribute("mallArticlePage", mallArticle);
		}
		return new ModelAndView("net/lahuobao/mall/admin/mallArticle");
	}
	
	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List<MallArticleEntity> list() {
		List<MallArticleEntity> listMallArticles=mallArticleService.getList(MallArticleEntity.class);
		return listMallArticles;
	}
	
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResponseEntity<?> get(@PathVariable("id") String id) {
		MallArticleEntity task = mallArticleService.get(MallArticleEntity.class, id);
		if (task == null) {
			return new ResponseEntity(HttpStatus.NOT_FOUND);
		}
		return new ResponseEntity(task, HttpStatus.OK);
	}

	@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
	@ResponseBody
	public ResponseEntity<?> create(@RequestBody MallArticleEntity mallArticle, UriComponentsBuilder uriBuilder) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<MallArticleEntity>> failures = validator.validate(mallArticle);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		mallArticleService.save(mallArticle);

		//按照Restful风格约定，创建指向新任务的url, 也可以直接返回id或对象.
		String id = mallArticle.getId();
		URI uri = uriBuilder.path("/rest/mallArticleController/" + id).build().toUri();
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(uri);

		return new ResponseEntity(headers, HttpStatus.CREATED);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<?> update(@RequestBody MallArticleEntity mallArticle) {
		//调用JSR303 Bean Validator进行校验，如果出错返回含400错误码及json格式的错误信息.
		Set<ConstraintViolation<MallArticleEntity>> failures = validator.validate(mallArticle);
		if (!failures.isEmpty()) {
			return new ResponseEntity(BeanValidators.extractPropertyAndMessage(failures), HttpStatus.BAD_REQUEST);
		}

		//保存
		mallArticleService.saveOrUpdate(mallArticle);

		//按Restful约定，返回204状态码, 无内容. 也可以返回200状态码.
		return new ResponseEntity(HttpStatus.NO_CONTENT);
	}

	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ResponseStatus(HttpStatus.NO_CONTENT)
	public void delete(@PathVariable("id") String id) {
		mallArticleService.deleteEntityById(MallArticleEntity.class, id);
	}

	/**
	 * 判断分类下只允许有一遍文章时，该分类下有没有文章
	 * @param categoryId
	 */
	@RequestMapping(value = "/ishave/{categoryId}", method = RequestMethod.POST)
	@ResponseBody
	public void ishave(@PathVariable("categoryId")String categoryId, HttpServletResponse response){
		MallJsonResult<String> json = new MallJsonResult<String>();
		try{
			List<MallArticleEntity> mallArticleEntities = mallArticleService.
					findByProperty(MallArticleEntity.class, "articlecategoryid", categoryId);
			if(mallArticleEntities.size() > 0){
				json.setHandleState(false);
				json.setMessage("该分类只允许有一遍文章，并且已存在文章！不能新增！");
			}else{
				json.setHandleState(true);
			}
		}catch (Exception e){
			json.setHandleState(false);
			e.printStackTrace();
		}finally {
			renderData(response, json);
		}
	}


}
